package com.hengpeng.itfinoss.controller.message;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hengpeng.common.persist.QueryResult;
import com.hengpeng.common.persist.entity.AbstractEntity.BoolValue;
import com.hengpeng.common.persist.query.model.Order.OrderType;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.common.web.tags.ListTag.Pagination;
import com.hengpeng.itfinbase.persist.Message;
import com.hengpeng.itfinbase.persist.Message.MessageSendType;
import com.hengpeng.itfinbase.persist.Message.MessageType;
import com.hengpeng.itfinoss.controller.BaseController;
import com.hengpeng.itfinoss.controller.util.PageHandlerUtil;
import com.hengpeng.itfinoss.service.ServiceFactory;
import com.hengpeng.itfinoss.util.PropertyClone;

/**
 * <pre>
 *  站内信控制器
 * </pre>
 * @author pengfangliang
 * @version 1.0, 2012-8-9
 */
@Controller
@RequestMapping("/message")
public class MessageController extends BaseController
{
	@Autowired
	private ServiceFactory serviceFactory;

	@RequestMapping("/new")
	public String preCreate(ModelMap map)
	{
		Message message = new Message();
		map.put("message", message);
		return "/message/create_message";
	}

	@RequestMapping
	public String create(HttpServletRequest request, Message message, ModelMap map)
	{
		try
		{
			if (validateObjectsNullOrEmpty(message.getTitle(), message.getContent(), message.getSummary(),
					message.getSendType()))
			{
				return PageHandlerUtil.returnError(map, "数据未通过验证,请刷新重试!");
			}
			message.setSender(getUserName(request.getSession()));
			message.setType(MessageType.IMPORTANT);
			message.setCreatDate(new Date());
			message.setReceiverTotal(0);// 根据发送条件统计发送人数
			message.setReadTotal(0);
			message.setReadRate(0);
			if (message.getIsPublish() != null && message.getIsPublish() == BoolValue.YES)
			{
				message.setPublishDate(new Date());
			}
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String[] isSetTimings = request.getParameterValues("set_timing");
			if (isSetTimings != null && isSetTimings.length != 0)
			{
				String sendTimeStr = request.getParameter("sendtime");
				if (StringHelper.isEmpty(sendTimeStr))
				{
					return PageHandlerUtil.returnError(map, "定时发送时间不能为空!");
				}
				else
				{
					message.setSendTime(format.parse(sendTimeStr));
				}
			}
			switch (message.getSendType())
			{
				case SINGLEMEMBER:
					String receiver = request.getParameter("receiver");
					if (StringHelper.isEmpty(receiver))
					{
						return PageHandlerUtil.returnError(map, "单个用户时收件人不能为空!");
					}
					if (receiver.contains(";"))
					{
						receiver = receiver.substring(0, receiver.length() - 1);
					}
					message.setUserName(receiver);
					break;
				default:
					break;
			}
			serviceFactory.getPersistService().save(message);
			return PageHandlerUtil.returnSuccess(map, "/message/list");
		}
		catch (Exception e)
		{
			return PageHandlerUtil.returnError(map, e.getMessage());
		}
	}

	@RequestMapping("/get/{id}")
	public String getMessage(HttpServletRequest request, @PathVariable Long id, ModelMap map)
	{
		try
		{
			Message message = serviceFactory.getPersistService().get(Message.class, id);
			if (message == null)
			{
				return PageHandlerUtil.returnError(map, "站内信不存在!");
			}
			if (message.getIsPublish() == BoolValue.YES)
			{
				return PageHandlerUtil.returnError(map, "已发布的信息不能再修改!");
			}
			map.put("message", message);
			return "/message/modify_message";
		}
		catch (Exception e)
		{
			return PageHandlerUtil.returnError(map, e.getMessage());
		}
	}

	@RequestMapping("/modify")
	public String modify(HttpServletRequest request, Message message, ModelMap map)
	{
		try
		{
			if (validateObjectsNullOrEmpty(message.getId(), message.getTitle(), message.getContent(),
					message.getSummary()))
			{
				return PageHandlerUtil.returnError(map, "数据未通过验证,请刷新重试!");
			}
			Message obj = serviceFactory.getPersistService().get(Message.class, message.getId());
			if (obj.getIsPublish() == BoolValue.YES)
			{
				return PageHandlerUtil.returnError(map, "已发布的信息不能再修改!");
			}
			if (message.getIsPublish() != null && message.getIsPublish() == BoolValue.YES)
			{
				message.setPublishDate(new Date());
			}
			PropertyClone.copyProperties(obj, message, false);
			serviceFactory.getPersistService().update(obj);
			return PageHandlerUtil.returnSuccess(map, "/message/list");
		}
		catch (Exception e)
		{
			return PageHandlerUtil.returnError(map, e.getMessage());
		}
	}

	@RequestMapping("/list")
	public String list(HttpServletRequest request, String title, MessageType type, MessageSendType sendType,
			BoolValue isPublish, String publishDate1, String publishDate2, ModelMap map, String userName)
	{
		map.put("title", title);
		map.put("type", type);
		map.put("sendType", sendType);
		map.put("isPublish", isPublish);
		map.put("publishDate1", publishDate1);
		map.put("publishDate2", publishDate2);
		map.put("userName", userName);
		Pagination page = new Pagination(request);
		page.setPageSize(this.getPageSize(request));
		try
		{
			DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			Date beginPublishDate = null;
			Date endPublishDate = null;
			if (StringHelper.isEmpty(title))
			{
				title = null;
			}
			if (!StringHelper.isEmpty(publishDate1))
			{
				beginPublishDate = format.parse(publishDate1);
			}
			if (!StringHelper.isEmpty(publishDate2))
			{
				endPublishDate = format.parse(publishDate2);
			}
			LinkedHashMap<String, OrderType> sortMap = new LinkedHashMap<String, OrderType>();
			sortMap.put("publishDate", OrderType.DESC);
			QueryResult<Message> result = serviceFactory.getMessageService().findMessageWithPage(title, type, sendType,
					isPublish, beginPublishDate, endPublishDate, userName, page.currentPage, page.pageSize, sortMap);
			page.setEntityCount((int) result.getTotalCount());
			map.put("list", result.getResults());
			map.put("listPage", page);
			return "/message/list";
		}
		catch (Exception e)
		{
			return PageHandlerUtil.returnError(map, e.getMessage());
		}
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(@RequestParam("fileToUpload") MultipartFile fileToUpload, ModelMap map)
	{
		InputStream stream = null;
		InputStreamReader sr = null;
		BufferedReader br = null;
		String result = "";
		try
		{
			byte[] by = fileToUpload.getBytes();
			stream = new ByteArrayInputStream(by);
			sr = new InputStreamReader(stream);
			br = new BufferedReader(sr);
			String text = br.readLine();
			while (text != null && text != "")
			{
				if (!text.trim().equals(""))
				{
					result += text.trim() + ";";
				}
				text = br.readLine();
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				br.close();
				sr.close();
				stream.close();
			}
			catch (Exception ex)
			{
				ex.printStackTrace();
			}
		}
		if (StringHelper.isEmpty(result))
		{
			result = result.substring(0, result.length() - 1);
		}
		return result;
	}
}
